package com.hz.hongbao.activities;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.GetCallback;
import com.awesome.android.sdk.publish.Bcloth;
import com.hz.hongbao.R;
import com.hz.hongbao.fragments.CommentSettingsFragment;
import com.hz.hongbao.fragments.GeneralSettingsFragment;
import com.hz.hongbao.utils.ConnectivityUtil;
import com.iflytek.voiceads.AdError;
import com.iflytek.voiceads.IFLYAdListener;
import com.iflytek.voiceads.IFLYAdSize;
import com.iflytek.voiceads.IFLYBannerAd;
import com.iflytek.voiceads.IFLYInterstitialAd;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.util.List;


public class MainActivity extends Activity implements AccessibilityManager.AccessibilityStateChangeListener {

    Bcloth bcloth;
    //开关切换按钮
    private TextView pluginStatusText;
    private ImageView pluginStatusIcon;
    //AccessibilityService 管理
    private AccessibilityManager accessibilityManager;
    private long exitTime = 0;
    private Context mContext;
    private boolean isShowAd = false;   //是否显示广告
    private LinearLayout layout_control_accessibility;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        bcloth = new Bcloth(MainActivity.this,"20161015000234","100487");
        bcloth.requestAwBcloth();

        pluginStatusText = (TextView) findViewById(R.id.layout_control_accessibility_text);
        pluginStatusIcon = (ImageView) findViewById(R.id.layout_control_accessibility_icon);
        layout_control_accessibility = (LinearLayout) findViewById(R.id.layout_control_accessibility);

        prepareSettings();
        handleMaterialStatusBar();
        explicitlyLoadPreferences();

        //监听AccessibilityService 变化
        accessibilityManager = (AccessibilityManager) getSystemService(Context.ACCESSIBILITY_SERVICE);
        accessibilityManager.addAccessibilityStateChangeListener(this);


        //分享
        findViewById(R.id.ll_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AVQuery<AVObject> avQuery = new AVQuery<>("ShareContent");
                avQuery.getInBackground("5807281f2f301e006c9d3027", new GetCallback<AVObject>() {
                    @Override
                    public void done(AVObject avObject, AVException e) {
                        String shareUrl = avObject.getString("shareUrl");
                        String shareText = avObject.getString("shareText");
                        String shareTitle = avObject.getString("shareTitle");

                        UMImage image = new UMImage(mContext, R.mipmap.ic_launcher);//资源文件
                        new ShareAction(MainActivity.this)
                                .withText(shareText)
                                .withMedia(image)
                                .withTargetUrl(shareUrl)
                                .withTitle(shareTitle)
                                .setDisplayList(SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN,SHARE_MEDIA.QZONE,SHARE_MEDIA.WEIXIN_CIRCLE)
                                .open();
                    }
                });


//                String value = AppConnect.getInstance(mContext).getConfig("sharecontent"
//                        ,"给大家分享一个超好用的微信自动抢红包工具！,http://hzapp.liisli.pub/");

//                Log.d("TAG","--------->"+value);
//                new ShareAction(MainActivity.this)
//                        .withText(value.split(",")[0])
//                        .withMedia(image)
//                        .withTargetUrl(value.split(",")[1])
//                        .withTitle("红包小助手")
//                        .setDisplayList(SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN,SHARE_MEDIA.QZONE,SHARE_MEDIA.WEIXIN_CIRCLE)
//                        .open();
            }
        });

        createBannerAd();

        createInterstitialAd();
    }



    public void createBannerAd() {
        String adUnitId = "795481FE6EB2837FDCE33C8E1BE69526";
        final IFLYBannerAd bannerView = IFLYBannerAd.createBannerAd(MainActivity.this, adUnitId);
        bannerView.setAdSize(IFLYAdSize.BANNER);
        bannerView.loadAd(new IFLYAdListener() {
            @Override
            public void onAdReceive() {
                bannerView.showAd();
            }
            @Override
            public void onAdFailed(AdError adError) {
            }
            @Override
            public void onAdClick() {
            }
            @Override
            public void onAdClose() {
            }
            @Override
            public void onAdExposure() {
            }
            @Override
            public void onConfirm() {
            }
            @Override
            public void onCancel() {
            }
        });


        LinearLayout layout_ads = (LinearLayout)findViewById(R.id.AdLinearLayout);
        layout_ads.removeAllViews();
        layout_ads.addView(bannerView);
    }

    public void createInterstitialAd() {
        final String adUnitId = "1C9B59436219DF343230AEA83C41FB89";
        final IFLYInterstitialAd interstitialAd  = IFLYInterstitialAd.createInterstitialAd(this, adUnitId);
        interstitialAd.setAdSize(IFLYAdSize.INTERSTITIAL);
        interstitialAd.loadAd(new IFLYAdListener(){
            @Override
            public void onAdReceive() {
                interstitialAd.showAd();
            }
            @Override
            public void onAdFailed(AdError error) {}
            @Override
            public void onAdClick() {}
            @Override
            public void onAdClose() {}
            @Override
            public void onAdExposure() {}
            @Override
            public void onCancel() {}
            @Override
            public void onConfirm() {}
        });
    }





    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private void explicitlyLoadPreferences() {
        PreferenceManager.setDefaultValues(this, R.xml.general_preferences, false);
    }

    private void prepareSettings() {
        String title, fragId;

//        Bundle bundle = getIntent().getExtras();
//        if (bundle != null) {
//            title = bundle.getString("title");
//            fragId = bundle.getString("frag_id");
//        } else {
//            title = "偏好设置";
//            fragId = "GeneralSettingsFragment";
//        }

            fragId = "GeneralSettingsFragment";

//        TextView textView = (TextView) findViewById(R.id.settings_bar);
//        textView.setText(title);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if ("GeneralSettingsFragment".equals(fragId)) {
            fragmentTransaction.replace(R.id.preferences_fragment, new GeneralSettingsFragment());
        } else if ("CommentSettingsFragment".equals(fragId)) {
            fragmentTransaction.replace(R.id.preferences_fragment, new CommentSettingsFragment());
        }
        fragmentTransaction.commit();
    }

    /**
     * 适配MIUI沉浸状态栏
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void handleMaterialStatusBar() {
        // Not supported in APK level lower than 21
        if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return;
        Window window = this.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(0xffE46C62);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Check for update when WIFI is connected or on first time.
        if (ConnectivityUtil.isWifi(this)){
            //检查更新
        }
        updateServiceStatus();

        if (bcloth != null) {
            bcloth.onResume();}

        if(isShowAd){   //显示广告
            if (bcloth!= null) {
                bcloth.showBcloth(false);
            }
            isShowAd = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //移除监听服务
        accessibilityManager.removeAccessibilityStateChangeListener(this);
        if (bcloth != null) {
            bcloth.onDestory();}
    }

    /**
     * 去打开权限
     * @param view
     */
    public void openAccessibility(View view) {
        try {
            isShowAd = true;
            Toast.makeText(this, "点击「红包小助手」" + pluginStatusText.getText(), Toast.LENGTH_SHORT).show();
            Intent accessibleIntent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
            startActivity(accessibleIntent);
        } catch (Exception e) {
            Toast.makeText(this, "遇到一些问题,请手动打开系统设置>无障碍服务>微信抢红包(ฅ´ω`ฅ)", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    public void enterAccessibilityPage(View view) {
        Intent mAccessibleIntent =
                new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        startActivity(mAccessibleIntent);
    }

    @Override
    public void onAccessibilityStateChanged(boolean enabled) {
        updateServiceStatus();
    }

    /**
     * 更新当前 HongbaoService 显示状态
     */
    private void updateServiceStatus() {
        if (isServiceEnabled()) {
            pluginStatusText.setText(R.string.service_off);
            pluginStatusIcon.setBackgroundResource(R.mipmap.ic_stop);
        } else {
            pluginStatusText.setText(R.string.service_on);
            pluginStatusIcon.setBackgroundResource(R.mipmap.ic_start);
        }
    }

    /**
     * 获取 HongbaoService 是否启用状态
     *
     * @return
     */
    private boolean isServiceEnabled() {
        List<AccessibilityServiceInfo> accessibilityServices =
                accessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_GENERIC);
        for (AccessibilityServiceInfo info : accessibilityServices) {
            if (info.getId().equals(getPackageName() + "/.services.HongbaoService")) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
//            System.exit(0);
        }
    }


    @Override
    protected void onPause() {
        if (bcloth != null) {
            bcloth.onPause();}
        super.onPause();
    }
    @Override
    public void onBackPressed() {
        if (bcloth.onBackPressed()) {
            return;}
        super.onBackPressed();
    }
}
